package com.winit.openapi.util;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.common.spring.SpringMessageLocator;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.exception.ValidationException;

/**
 * 校验工具类
 * @author kang.wang 2015-1-8 上午10:30:50
 * @since 1.0
 */
public class ValidateUtil {
    
	public final static String DATE_PATTERN_BASE = "yyyy-MM-dd HH:mm:ss";
	public final static String REG_EMAIL = "^[a-zA-Z0-9_\\.]+@[a-zA-Z0-9-]+[\\.a-zA-Z]+$";
	
	private final static String NUMBER = "^[0-9]*$";

	public static final String VALIDATOR = "validator";

    public static boolean isNotNull(JSONObject json,String key){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(obj != null && StringUtils.isNotBlank(obj.toString()))
                return true;
        }
        return false;
    }
    
    //验证数字的最大值
    public static void validNumberMax(JSONObject json,BigDecimal maxNumber,String key){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                String s = obj.toString();
                BigDecimal bd = null;
                try {
                    bd = new BigDecimal(s);
                    if(bd.compareTo(maxNumber)>0){
                        throw new ApiException(ErrorCode.FIELD_MAX, key,maxNumber);
                    }
                } catch (NumberFormatException e) {
                    throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, key);
                }
            }
        }
    }
    
    //数字的最大0
    public static void validNumberBiggerThanZero(JSONObject json,String key){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                String s = obj.toString();
                BigDecimal bd = null;
                try {
                    bd = new BigDecimal(s);
                    if(!(bd.compareTo(BigDecimal.ZERO)>0)){
                        throw new ApiException(ErrorCode.FIELD_MUST_BE_BIGGER_THAN_ZERO, key);
                    }
                } catch (NumberFormatException e) {
                    throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, key);
                }
            }
        }
    }
    
    
    //批量导入提示，返回xmlKey的提示字段
    public static void validImportNotNull(JSONObject json,String key,String xmlKey){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(obj != null && StringUtils.isNotBlank(obj.toString()))
                return;
        }
        throw new ApiException(ErrorCode.FIELD_NOT_NULL, xmlKey);
    }
    
    /**
     * 
     * 校验整数位长度限制、小数位长度限制
     * @param json
     * @param key
     * @param 整数位长度限制
     * @param 小数位长度限制
     */
    public static void validatePrecisionImport(JSONObject json,String key,String xmlKey,int intLength,int precisionLength){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                String s = obj.toString();
                int index = s.indexOf(".");
                if(index > 0){
                    int aCount = s.substring(0,index).length();
                    if(aCount > intLength){
                        throw new ApiException(ErrorCode.FIELD_INT_TOLONG_ERROR, xmlKey,intLength);
                    }
                    int bCount = s.substring(index+1).length();
                    if(bCount > precisionLength){
                        throw new ApiException(ErrorCode.FIELD_PRECISION_TOLONG_ERROR, xmlKey,precisionLength);
                    }
                }else{
                    int aCount = s.length();
                    if(aCount > intLength){
                        throw new ApiException(ErrorCode.FIELD_INT_TOLONG_ERROR, xmlKey,intLength);
                    }
                }
            }
        }
    }
    
    
    /**
     * 
     * 校验小数位长度限制
     * @param json
     * @param key
     * @param 整数位长度限制
     * @param 小数位长度限制
     */
    public static void validatePrecision(JSONObject json,String key,String xmlKey,int precisionLength){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                String s = obj.toString();
                int index = s.indexOf(".");
                if(index > 0){
                    int bCount = s.substring(index+1).length();
                    if(bCount > precisionLength){
                        throw new ApiException(ErrorCode.FIELD_PRECISION_TOLONG_ERROR, xmlKey,precisionLength);
                    }
                }
            }
        }
    }
    /**
     * 
     * 校验整数位长度限制、小数位长度限制
     * @param json
     * @param key
     * @param 整数位长度限制
     * @param 小数位长度限制
     */
    public static void validatePrecision(JSONObject json,String key,int intLength,int precisionLength){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                String s = obj.toString();
                int index = s.indexOf(".");
                if(index > 0){
                    int aCount = s.substring(0,index).length();
                    if(aCount > intLength){
                        throw new ApiException(ErrorCode.FIELD_INT_TOLONG_ERROR, key,intLength);
                    }
                    int bCount = s.substring(index+1).length();
                    if(bCount > precisionLength){
                        throw new ApiException(ErrorCode.FIELD_PRECISION_TOLONG_ERROR, key,precisionLength);
                    }
                }else{
                    int aCount = s.length();
                    if(aCount > intLength){
                        throw new ApiException(ErrorCode.FIELD_INT_TOLONG_ERROR, key,intLength);
                    }
                }
            }
        }
    }
    /**
     * 
     * 校验整数位长度限制、小数位长度限制,抛出其他提示
     * @param json
     * @param key
     * @param 整数位长度限制
     * @param 小数位长度限制
     */
    public static void validatePrecisionOtherReminder(JSONObject json,String key,String reminderKey,int intLength,int precisionLength){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                String s = obj.toString();
                int index = s.indexOf(".");
                if(index > 0){
                    int aCount = s.substring(0,index).length();
                    if(aCount > intLength){
                        throw new ApiException(ErrorCode.FIELD_INT_TOLONG_ERROR, reminderKey,intLength);
                    }
                    int bCount = s.substring(index+1).length();
                    if(bCount > precisionLength){
                        throw new ApiException(ErrorCode.FIELD_PRECISION_TOLONG_ERROR, reminderKey,precisionLength);
                    }
                }else{
                    int aCount = s.length();
                    if(aCount > intLength){
                        throw new ApiException(ErrorCode.FIELD_INT_TOLONG_ERROR, reminderKey,intLength);
                    }
                }
            }
        }
    }
    //批量导入，返回xmlKey提示
    public static void validBigDecimalImport(JSONObject json,String key,String xmlKey,boolean...required){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                String s = obj.toString();
                try {
                    new BigDecimal(s);
                } catch (NumberFormatException e) {
                    throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, xmlKey);
                }
            }else{
                if(required.length > 0 && required[0]){
                    throw new ApiException(ErrorCode.FIELD_NOT_NULL, xmlKey);
                }
            }
        }
    }
    
    public static void validImportMaxLength(JSONObject json,String key,String xmlKey,int maxLength,boolean...required){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                String s = obj.toString();
                if(s.length() > maxLength){
                    throw new ApiException(ErrorCode.FIELD_LENGTH_TO_LONG, xmlKey,maxLength);
                }
            }else{
                if(required.length > 0 && required[0]){
                    throw new ApiException(ErrorCode.FIELD_NOT_NULL, xmlKey);
                }
            }
        }
    }
    public static void validList(JSONObject json,String key,boolean...required){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(obj != null){
                if(obj instanceof JSONArray){
                    return;
                }else{
                    throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, key);
                }
            }else{
                if(required.length > 0 && required[0]){
                    throw new ApiException(ErrorCode.FIELD_NOT_NULL, key);
                }
            }
        }
    }
    public static void validListOtherReminder(JSONObject json,String key,String reminderKey,boolean...required){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(obj != null){
                if(obj instanceof JSONArray){
                    return;
                }else{
                    throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, reminderKey);
                }
            }else{
                if(required.length > 0 && required[0]){
                    throw new ApiException(ErrorCode.FIELD_NOT_NULL, reminderKey);
                }
            }
        }
    }
    private static Validator getValidator(){
        LocalValidatorFactoryBean validator = (LocalValidatorFactoryBean) SpringUtil.getBean(VALIDATOR);
        return validator.getValidator();
    }
    
    /**
     * 校验不通过抛出异常
     * @param validator
     * @param obj
     */
    public static void validateWithExp(Object obj){
        
        Set<ConstraintViolation<Object>> set = getValidator().validate(obj);
        if(set != null && set.size() > 0){
            for (ConstraintViolation<?> c : set) {
                String code = getErrorCode(c);
                String msg = getErrorMsg(c);
                throw new ValidationException(code, msg);
            }
        }
    }
    
    
    private static String getErrorCode(ConstraintViolation<?> c){
        String code = c.getMessageTemplate();
        code = code.replace("{", "").replace("}", "");
        return code;
    }
    
    private static String getErrorMsg(ConstraintViolation<?> c){
    	String code = getErrorCode(c);
    	String field = c.getPropertyPath().toString();
       Map<String, Object> map=c.getConstraintDescriptor().getAttributes();
  
    	String msg = SpringMessageLocator.getMessage(code, new String[]{field}, CommandContext.getContext().getLocale());
  
    	if(c.getConstraintDescriptor().getAnnotation().annotationType() .equals(javax.validation.constraints.Digits.class) 
    			&&null!=msg&&msg.indexOf("{1}")!=-1&&null!=map&&map.containsKey("integer")){
    		msg = msg.replace("{1}", map.get("integer").toString());
    	}
    	 
    	if(c.getConstraintDescriptor().getAnnotation().annotationType().
    			equals(org.hibernate.validator.constraints.Length.class)
    			&&null!=msg&&msg.indexOf("{1}")!=-1&&null!=map&&map.containsKey("max")){
    		msg = msg.replace("{1}", map.get("max").toString());
    	}
    	
        return msg;
    }
    
    public static boolean isLongNumber(String str) {
		if (str == null || "".equals(str)) {
			return false;
		} 
		boolean result = false;
		try {
			Long.parseLong(str);
			result = true;
		} catch (Exception e) {
		}

		return result;
	}
    

    public static boolean isNotNull(String str) {
		if (str != null) {
			return true;
		}
		return false;
	}


    public static String trimString(String str) {
		String result = null;
		if (isNotNull(str)) {
			result = str.trim();
		} else {
			result = str;
		}

		return result;
	}

    public static boolean isFloat(String str) {
		if (isNullOrEmpty(str)) {
			return false;
		}
		try {
			Float.parseFloat(str);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
    public static Date getDate(String str, DateFormat df) {
		Date date = null;
		try {
			date = df.parse(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return date;
	}
    public static boolean isNullOrEmpty(String str) {
		boolean flag = false;
		if (str == null || "".equals(str)) {
			flag = true;
		}
		return flag;
	}
    
    public static boolean isBigDecimal(String str) {
		if (isNullOrEmpty(str)) {
			return false;
		}
		try { 
			new BigDecimal(str); 
			return true;
		} catch (Exception e) {
			return false;
		}
	}
    
    public static boolean isDateFormat(String str, SimpleDateFormat df) {
		boolean result = false;
		try { 
			if (df.parse(str) != null&&df.toPattern().length()==str.length()) {
				result = true;
			}
		} catch (Exception e) {
		}

		return result;
	}

 
    public static boolean isIntNumber(String str) {
		if (str == null || "".equals(str)) {
			return false;
		}

		boolean result = false;
		try {
			Integer.parseInt(str);
			result = true;
		} catch (Exception e) {
		}

		return result;
	}
    
    /**
     * 需传入抛出提示字段reminderKey
     * @param json
     * @param key
     * @param reminderKey
     */
    public static void validEmailOtherReminder(JSONObject json,String key,String reminderKey){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                String e = obj.toString();
                if(e.indexOf("@")==-1||e.lastIndexOf("@")>e.lastIndexOf(".")){
                	 throw new ApiException(ErrorCode.EMAIL_TYPE_ERR,reminderKey);	
                }
//                if(!e.matches(REG_EMAIL)){
//                    throw new ApiException(ErrorCode.EMAIL_TYPE_ERR,key);
//                }
            }
        }
    }
    
    public static void validMustNumber(JSONObject json,String key){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                String e = obj.toString();
                if(!e.matches(NUMBER)){
                  throw new ApiException(ErrorCode.MUST_NUMBER,key);
              }
            }
        }
    }
    
   // 判断非必填字段是否有值
    public static boolean isExistValue(JSONObject jsonObject, String key) {
        if (jsonObject.containsKey(key)) {
            return !"".equals(jsonObject.getString(key));
        }
        return false;
    } 
    
    public static void validDateBefore(JSONObject json,String start,String end){
        if(json.containsKey(start) && json.containsKey(end)){
            Object obj1 = json.get(start);
            Object obj2 = json.get(end);
            if(obj1 != null && StringUtils.isNotBlank(obj1.toString())
                    && obj2 != null && StringUtils.isNotBlank(obj2.toString())){
                String e1 = obj1.toString();
                String e2 = obj2.toString();
                Date d1 = DateUtil.parse2Date(e1, DateUtil.SIMPLE_DATE_STRING);
                Date d2 = DateUtil.parse2Date(e2, DateUtil.SIMPLE_DATE_STRING);
                if(d2.before(d1)){
                    throw new ApiException(ErrorCode.START_AFTER_END,start,end);
                }
            }
        }
    }
 
    /**
     * 参数校验
     * @param json json对象
     * @param name 参数名称 
     * @param length 参数最大长度
     * @param 是否校验参数长度
     */
    public static void valid(JSONObject json,String name,int length,boolean isMachLen){
 	    ValidateUtil.validNotNull(json, name);
 	    if(isMachLen){
 	    	ValidateUtil.validMaxLength(json, name, length);
 	    }
        
    }
    
    public static void validNotNull(JSONObject json,String key){
        validNotNull(json, key, null);
    }

    /**
     * 异常提示使用别名
     * @param json
     * @param key
     * @param aliasKey
     */
    public static void validNotNull(JSONObject json,String key, String aliasKey){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(obj != null && StringUtils.isNotBlank(obj.toString()))
                return;
        }
        if(StringUtils.isNotBlank(aliasKey)){
            key = aliasKey;
        }
        throw new ApiException(ErrorCode.FIELD_NOT_NULL, key);
    }
    
    public static void validInteger(JSONObject json,String key,boolean...required){
        validInteger(json, key, null, required);
    }
    
    public static void validInteger(JSONObject json,String key, String aliasKey, boolean...required){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(StringUtils.isNotBlank(aliasKey)){
                key = aliasKey;
            }
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                String s = obj.toString();
                try {
                    Integer.parseInt(s);
                } catch (NumberFormatException e) {
                    throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, key);
                }
            }else{
                if(required.length > 0 && required[0]){
                    throw new ApiException(ErrorCode.FIELD_NOT_NULL, key);
                }
            }
        }
    }
    
    public static void validBigDecimal(JSONObject json,String key,boolean...required){
        validBigDecimal(json, key, null, required);
    }
    
    public static void validBigDecimal(JSONObject json,String key, String aliasKey, boolean...required){
        if(json.containsKey(key)){  
            Object obj = json.get(key);
            if(StringUtils.isNotBlank(aliasKey)){
                key = aliasKey;
            }
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                String s = obj.toString();
                try {
                    new BigDecimal(s);
                } catch (NumberFormatException e) {
                    throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, key);
                }
            }else{
                if(required.length > 0 && required[0]){
                    throw new ApiException(ErrorCode.FIELD_NOT_NULL, key);
                }
            }
        }
    }
    
    public static void validMaxLength(JSONObject json,String key,int maxLength,boolean...required){
        validMaxLength(json, key, null, maxLength, required);
    }
    
    public static void validMaxLength(JSONObject json,String key, String aliasKey, int maxLength,boolean...required){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(StringUtils.isNotBlank(aliasKey)){
                key = aliasKey;
            }
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                String s = obj.toString();
                if(s.length() > maxLength){
                    throw new ApiException(ErrorCode.FIELD_LENGTH_TO_LONG, key,maxLength);
                }
            }else{
                if(required.length > 0 && required[0]){
                    throw new ApiException(ErrorCode.FIELD_NOT_NULL, key);
                }
            }
        }
    }
    
    public static void validMaxLengthTrim(JSONObject json,String key, String aliasKey, int maxLength,boolean...required){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(StringUtils.isNotBlank(aliasKey)){
                key = aliasKey;
            }
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                String s = obj.toString().trim();
                if(s.length() > maxLength){
                    throw new ApiException(ErrorCode.FIELD_LENGTH_TO_LONG, key,maxLength);
                }
            }else{
                if(required.length > 0 && required[0]){
                    throw new ApiException(ErrorCode.FIELD_NOT_NULL, key);
                }
            }
        }
    }
    
    /**
     * 保留小数点后两位
     * @param json
     * @param key
     * @param maxLength
     * @param required
     */
    public static void validMaxLengthTwo(JSONObject json,String key, String aliasKey, int maxLength,boolean...required){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(StringUtils.isNotBlank(aliasKey)){
                key = aliasKey;
            }
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                String s = obj.toString();
                if(s.length() > maxLength){
                    throw new ApiException(ErrorCode.FIELD_LENGTH_TO_LONG, key,maxLength);
                }
                //获取小数点的位置
                int num=s.indexOf(".");
                if(num!=-1)
                {
                    //获取小数点后面的数字是否有两位 不足两位补足两位
                    String dianAfter=s.substring(0,num+1);
                    String nnString=s.replace(dianAfter, "");
                    if(nnString.length()>2)
                    {
                        throw new ApiException(ErrorCode.FIELD_DECIMAL_POINT_BEYOND_TWO, key,maxLength);
                    }
                }
            }else{
                if(required.length > 0 && required[0]){
                    throw new ApiException(ErrorCode.FIELD_NOT_NULL, key);
                }
            }
        }
    }


    public static void validDateString(JSONObject json,String key,String format){
        validDateString(json, key, null, format);
    }
    
    public static void validDateString(JSONObject json,String key, String aliasKey, String format){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(StringUtils.isNotBlank(aliasKey)){
                key = aliasKey;
            }
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                String value = obj.toString();
                Date date = DateUtil.parse2Date(value,format);
                String v = DateUtil.parse2String(date,format);
                if(!value.equals(v)){
                    throw new ApiException(ErrorCode.FIELD_TYPE_ERROR,key);
                }
            }
        }
    }
    
    public static void validEmail(JSONObject json,String key){
        validEmail(json,key, null);
    }
    
    public static void validEmail(JSONObject json,String key, String aliasKey){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(StringUtils.isNotBlank(aliasKey)){
                key = aliasKey;
            }
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                String e = obj.toString();
                if(e.indexOf("@")==-1||e.lastIndexOf("@")>e.lastIndexOf(".")){
                     throw new ApiException(ErrorCode.EMAIL_TYPE_ERR,key);  
                }
            }
        }
    }
     /**
      * 验证正则
      * @param json
      * @param key
      * @param regex
      */
    public static void validByRegex(JSONObject json,String key, String regex ,String aliasKey){
        if(json.containsKey(key)){
            Object obj = json.get(key);
            if(StringUtils.isNotBlank(aliasKey)){
                key = aliasKey;
            }
            if(obj != null && StringUtils.isNotBlank(obj.toString())){
                //必须是字母或数字
                if(!obj.toString().matches(regex)){
                     throw new ApiException(ErrorCode.MUST_BE_LETTERS_OR_NUMBERS,key);  
                }
            }
        }
    }
	
    /**
     * 验证正则
     * @param json
     * @param key
     * @param regex
     */
   public static void validByRegex(JSONObject json,String key, String regex,boolean ...flag){
       if(json.containsKey(key)){
           Object obj = json.get(key);
           if(flag.length > 0 && flag[0] && null == obj){
               throw new ApiException(ErrorCode.FIELD_NOT_NULL,key);
           }
           if(obj != null && StringUtils.isNotBlank(obj.toString())){
               if(!obj.toString().matches(regex)){
                    throw new ApiException(ErrorCode.REGEX_IS_ERROR,key,regex);  
               }
           }
       }
   }
	
	  public static void validNotNegativeNumber(JSONObject json,String key){
        if(json.containsKey(key)){
            BigDecimal num = new BigDecimal(0);
            try
            {
                num = json.getBigDecimal(key);
            }catch (Exception e) {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, key);
            }
            if(num.intValue() < 0){
                throw new ApiException(ErrorCode.COMPLETE_TO_ZERO, key);
            }
        }
    }
	
	public static void typeValidate(JSONObject json, String key, String[] constants, boolean... required) {
        if (json.containsKey(key)) {
            Object obj = json.get(key);
            if (obj != null) {
                if (!Arrays.asList(constants).contains(obj.toString())) {
                    throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, key);
                }
            } else {
                if (required.length > 0 && required[0]) {
                    throw new ApiException(ErrorCode.FIELD_NOT_NULL, key);
                }
            }
        } else {
            if (required.length > 0 && required[0]) {
                throw new ApiException(ErrorCode.FIELD_NOT_NULL, key);
            }
        }
    }
	 public static void validNotZreo(JSONObject json,String key){
	     validNotZreo(json, key, null); 
	    }
	    
    public static void validNotZreo(JSONObject json, String key, String aliasKey) {
        if (json.containsKey(key)) {
            Object obj = json.get(key);
            if (obj != null && StringUtils.isNotBlank(obj.toString())) {
                String s = obj.toString();
                try {
                    BigDecimal a = new BigDecimal(s); 
                    if (!(a.compareTo(BigDecimal.ZERO)==1)) {
                        throw new ApiException(ErrorCode.FIELD_NOT_ZREO_VALUE_ERROR, key);
                    }
                } catch (NumberFormatException e) {
                    throw new ApiException(ErrorCode.FIELD_VALUE_ERROR, key);
                }
            }
        }
    }

    /**
     * 验证字段方法
     * 
     * @param field 字段对象
     * @param fieldName 字段名
     * @param required 验证是否为空标识 true:必填 false:非必填
     * @param maxLength 验证长度标识和长度参数
     * @param isInteger 验证数值类型标识
     */
    public static void valid(JSONObject json, String fieldName, boolean required, boolean isInteger, Integer maxLength) {

        if (required) {
            validNotNull(json, fieldName);
        }
        
        if (isInteger) {
            validInteger(json, fieldName, null);
        }
        
        if (maxLength != null) {
            validMaxLength(json, fieldName, maxLength, required);
        }

    }
	
    public static void main(String[] args) {
        JSONObject json = new JSONObject();
        json.put("weight", "0.7");
        json.put("te", "");
       valid(json, "te", false, true, 1);
    }
    
}
